const { Announcement } = require('../models')

class AnnouncementService {
  /**
   * 创建新公告
   * @param {Object} announcementData 公告数据
   * @returns {Promise<Object>} 创建的公告对象
   */
  async createAnnouncement(announcementData) {
    try {
      const newAnnouncement = await Announcement.create({
        content: announcementData.content,
        publish_time: announcementData.publishTime || new Date(),
      })

      return newAnnouncement
    } catch (error) {
      throw error
    }
  }

  /**
   * 获取所有公告
   * @returns {Promise<Array>} 公告列表
   */
  async getAllAnnouncements() {
    try {
      const announcements = await Announcement.findAll({
        order: [['publish_time', 'DESC']], // 按发布时间降序排序
      })

      return announcements
    } catch (error) {
      throw error
    }
  }

  /**
   * 更新公告
   * @param {Number} id 公告ID
   * @param {Object} announcementData 更新的公告数据
   * @returns {Promise<Object>} 更新后的公告对象
   */
  async updateAnnouncement(id, announcementData) {
    try {
      const announcement = await Announcement.findByPk(id)

      if (!announcement) {
        throw new Error('公告不存在')
      }

      // 更新公告信息
      announcement.content = announcementData.content || announcement.content
      if (announcementData.publishTime) {
        announcement.publish_time = announcementData.publishTime
      }
      await announcement.save()
      return announcement
    } catch (error) {
      throw error
    }
  }

  /**
   * 删除公告
   * @param {Number} id 公告ID
   * @returns {Promise<Boolean>} 操作成功返回true
   */
  async deleteAnnouncement(id) {
    try {
      const announcement = await Announcement.findByPk(id)
      if (!announcement) {
        throw new Error('公告不存在')
      }
      await announcement.destroy()
      return true
    } catch (error) {
      throw error
    }
  }
}

module.exports = new AnnouncementService()
